package com.wjf.userservice.mapper;

import com.wjf.userservice.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.*;
import java.util.Date;

/**
 * 用户数据访问层接口
 * 处理用户相关的数据库操作
 */
@Mapper
public interface UserMapper {
    
    /**
     * 根据用户名查询用户信息（包含角色和权限）
     */
    @Select("SELECT * FROM user WHERE username = #{username}")
    @Results({
        @Result(id = true, property = "id", column = "id"),
        @Result(property = "roles", column = "id",
            many = @Many(select = "com.wjf.userservice.mapper.RoleMapper.findRolesByUserId")),
        @Result(property = "permissions", column = "id",
            many = @Many(select = "com.wjf.userservice.mapper.RoleMapper.findPermissionsByUserId"))
    })
    User findByUsername(String username);
    
    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @return 用户对象，如果验证失败返回null
     */
    @Select("SELECT * FROM user WHERE username = #{username} AND password = #{password}")
    User login(@Param("username") String username, @Param("password") String password);
    
    /**
     * 注册新用户
     * @param user 用户对象，包含注册信息
     * @return 影响的行数，成功返回1
     */
    @Insert("INSERT INTO user (username, password, nickname, email, phone, status, " +
            "vip_level, create_time) VALUES (#{username}, #{password}, #{nickname}, " +
            "#{email}, #{phone}, #{status}, #{vipLevel}, #{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int register(User user);
    
    /**
     * 检查用户名是否已存在
     * @param username 待检查的用户名
     * @return 存在返回1，不存在返回0
     */
    @Select("SELECT COUNT(*) FROM user WHERE username = #{username}")
    int checkUsername(String username);
    
    /**
     * 选择性更新用户信息
     */
    int updateUser(User user);
    
    /**
     * 更新用户密码
     */
    @Update("UPDATE user SET password = #{newPassword}, " +
            "update_time = #{updateTime} WHERE id = #{id}")
    int updatePassword(@Param("id") Long id, 
                      @Param("newPassword") String newPassword, 
                      @Param("updateTime") Date updateTime);

    @Insert("INSERT INTO user_role (user_id, role_id, create_time) " +
            "VALUES (#{userId}, #{roleId}, #{createTime})")
    int assignUserRole(@Param("userId") Long userId, 
                      @Param("roleId") Long roleId,
                      @Param("createTime") Date createTime);

    /**
     * 检查用户名是否存在（排除当前用户）
     */
    @Select("SELECT COUNT(*) FROM user WHERE username = #{username} AND id != #{userId}")
    int checkUsernameExist(@Param("username") String username, @Param("userId") Long userId);

    /**
     * 检查邮箱是否存在（排除当前用户）
     */
    @Select("SELECT COUNT(*) FROM user WHERE email = #{email} AND id != #{userId}")
    int checkEmailExist(@Param("email") String email, @Param("userId") Long userId);

    /**
     * 检查手机号是否存在（排除当前用户）
     */
    @Select("SELECT COUNT(*) FROM user WHERE phone = #{phone} AND id != #{userId}")
    int checkPhoneExist(@Param("phone") String phone, @Param("userId") Long userId);
}
